using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Net.Http
{
    public static class HttpExtensions
    {
        /// <summary>
        /// 将字符串字典中的全部键值添加到MultipartFormDataContent中
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dic"></param>
        public static void AddDictory(this MultipartFormDataContent data, Dictionary<string, string> dic)
        {
            if (dic != null)
            {
                foreach (var item in dic)
                {
                    data.Add(item.Key, item.Value);
                }
            }
        }
        /// <summary>
        /// 添加字符串数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void Add(this MultipartFormDataContent data, string name, string value)
        {
            data.Add(new StringContent(value), name);
        }

        public static async Task<ApiResult> GetApiResult(this HttpResponseMessage resp)
        {
            if (resp.Content==null)
            {
                throw new Exception("HttpResponseMessage.Content为空。");
            }
            var res = await resp.Content.ReadAsStringAsync();
            ApiResult api = null;
            try
            {
                api = JsonConvert.DeserializeObject<ApiResult>(res);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return api;
        }
    }
}
